﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.AutoUpdate;
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.Models;
using DWF.Studio.Share.Log;
using DWF.Studio.Share.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DWF.Studio.Services
{
    internal class SysUpgradeService : ISysUpgradeService
    {
        private UpdateManager _updateManager = null;

        private IConfigService _configService = null;

        private IAppService _appService = null;

        CancellationTokenSource cancellationTokenSource = null;
        public SysUpgradeService(IAppService appService)
        {
            _appService = appService;
            _configService = new ConfigService();
            var sysConfig = _configService.LoadSysConfig();
            _updateManager = new UpdateManager(sysConfig.UpgradeUri);
            
        }

        public async Task<SysVersionInfo> GetLastestVersionAsync()
        {
            SysVersionInfo sysVersion = null;

            var version = await Task.Factory.StartNew(() =>
            {
                return _updateManager.GetLasestVersion("GetStudioVersion");
            });

            if (version != null)
            {
                sysVersion = new SysVersionInfo()
                {
                    Version = version.Version,
                    UpgradeTime = version.UpdateTime,
                    DownloadUrl = version.DownloadUrl,
                    Description = version.Description
                };
            }

            return sysVersion;
        }

        public async Task<string> DownloadPackageAsync(string downloadUri, Action<long, long> downloadStatus = null)
        {
            var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var upgradePath = System.IO.Path.Combine(localAppData, StaticResource.ProcessGo, StaticResource.Studio, StaticResource.Upgrade);
            cancellationTokenSource = new CancellationTokenSource();
            if (!FileHelper.CheckFolderExisting(upgradePath))
            {
                FileHelper.CreateFolder(upgradePath);
            }
            
            string fullName = null;
            await Task.Factory.StartNew((CancellationToken) =>
            {
                _updateManager.NowUpdate(downloadUri, upgradePath,
                (result, fileName) =>
                {
                    if (result)
                    {
                        fullName = fileName;
                    }
                },
                downloadStatus
                );
            }, TaskCreationOptions.LongRunning, cancellationTokenSource.Token);

            return fullName;
        }

        public void Upgrade(string file)
        {
            _appService.Close();
            System.Diagnostics.Process.Start(file);
        }

        public void CancelDownload()
        {
            cancellationTokenSource.Cancel();
            _updateManager.IsCancelled = true;
            cancellationTokenSource = null;
        }
    }
}
